package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author ：混元太极门
 * @date ：Created in 2022年06月09日
 * @description ：
 * @version: 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired  //预约
    private OrderDao orderDao;
    @Override
    @Transactional//事务管理
    public Order add(Order order) {
         log.info("预约业务开启:",order);
         //预约设置信息                                             获取预约时间
        OrderSetting orderSetting = orderSettingDao.selectOrder(order.getOrderDate());
        //判断能不能预约了
        if (orderSetting == null){
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);//用户选的日期能不能预约
        }else {
            if (orderSetting.getReservations()>=orderSetting.getNumber()){
           //如果可以预约  但是约满 就提示他预约已满        异常处理
                throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
            }
            //查询是否有相同的用户重复预约的  重复的用户和套餐   获取套餐id             获取预约时间            获取会员id
            long chongfu = orderDao.chongfuMemberAndSetMeal(order.getSetmealId(),order.getOrderDate(),order.getMemberId());
            //判断
            if (chongfu>0){     //告送用户您已经预约不能在预约了
                throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
            }
            //添加数据   预约表
           // orderDao.addOrder(order);
            //修改用户已经预约的人数      预约成功就加一
            orderSettingDao.updateReservationsById(orderSetting.getId(),orderSetting.getReservations()+1);
        }
        return orderDao.selectById(order.getId());
    }

    @Override
    public List<Map<String, Object>> countBySetmeal() {
        return orderDao.countBySetmeal();
    }

    /**
     * 查询预约表id
     * @param id
     * @return
     */
    @Override
    public Order findById(Integer id) {
        return orderDao.selectById(id);
    }
}
